﻿using System.Collections.Generic;
using System.IO;
using Actya.Web.Infrastructure.ElFinderConnector.Responses;
using Actya.Web.Infrastructure.ElFinderConnector.Utils;

namespace Actya.Web.Infrastructure.ElFinderConnector.Commands
{
    public class Tmb : ICommand
    {
        public string Current { get; set; }

        public Tmb(string current)
        {            
            this.Current = current;            
        }

        #region ICommand Members       

        public Response Execute()
        {
            var path = DirectoryUtils.GetRelativePathByHash(Current);

            var response = new ThumbnailResponse();

            response.current = Current;

            response.tmb = false;

            var images = new Dictionary<string, string>();

            var directoryInfo = new System.IO.DirectoryInfo(path);

            var patterns = "*.jpg,*.jpeg,*.png,*.gif,*.bmp".Split(",".ToCharArray());

            var files = new List<FileInfo>();
            foreach (var pattern in patterns)
            {
                files.AddRange(directoryInfo.GetFiles(pattern));
            }

            var i = 0;

        	var tmbDir = new DirectoryInfo(Configuration.Configuration.TmbDir);
        	tmbDir.EnsureExists();

            foreach (var file in files)
            {   
                var tmbName = file.FullName.Hash();
                var tmbPath = Path.Combine(Configuration.Configuration.TmbDir, string.Format("{0}.png", tmbName));
                if (!File.Exists(tmbPath))
                {
                    i++;
                    if (i > Configuration.Configuration.TmbsAtOnce)
                    {
                        response.tmb = true;
                        break;
                    }

                    ImageUtils.Resize(file.FullName, tmbPath, 48, 48, System.Drawing.Imaging.ImageFormat.Png, "thumbnail", 0, 0);
                    images.Add(tmbName, string.Format("{0}/{1}.png", Configuration.Configuration.TmbUrl, tmbName));
                }
            }

            if (images.Count > 0)
            {
            	response.images = images;
            }

            return response;
        }

        #endregion
    }
}
